<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios基本使用</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
</body>
<script>
    /*  npx json-server --watch db.json */
    axios.defaults.baseURL='http://localhost:3000/posts'
    const btn = document.querySelectorAll('button');
    btn[0].onclick =function(){
        axios({
            method:'GET',
            url:'/2',
        }).then(response=>{
            console.log(response);
        });
    }
    //POST添加数据
    btn[1].onclick = function(){
        axios({
            method:'POST',
            url:'',
            data:{
                id:3,//若不给定ID，则每次会在前一次请求的ID上自动加一
                title:'今天是2022年10月9日21点52分正在学习使用axios',
                author:'轨迹'
            }
        }).then(response=>{
            console.log(response);
        })
    }
    //PUT请求更新改变指定id的数据
    btn[2].onclick=function(){
        axios({
            method:'PUT',
            url:'/3',
            data:{
                title:'使用PUT请求更新数据',
                author:'怎么会',
            }
    }).then(response=>{
                console.log(response);
            })
    }
    //delete请求删除数据
    btn[3].onclick = function(){
        axios({
            method:'delete',
            url:'/3',
        }).then(response=>{
            console.log(response);
        })
    }
</script>
</html>